package com.woof.petfinder;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Spinner;

public class TestPetfinderActivity extends Activity implements Constants {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main); 
        selectedAnimal = null;
        
        
        Spinner animals = (Spinner)this.findViewById(R.id.animals);
        animals.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent,
			        View view, int pos, long id) {
				parent.setSelection(pos);
				selectedAnimal = parent.getSelectedItem().toString().toLowerCase();
				getBreeds.setEnabled(true);
				breeds.setEnabled(true);
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				// TODO Auto-generated method stub
			}
		});
        
        breeds = (Spinner)this.findViewById(R.id.breeds);
        breeds.setEnabled(false);
        breedsAdapter = new ArrayAdapter<String>(getApplicationContext(), 
        		android.R.layout.simple_spinner_item, new ArrayList<String>());
        breeds.setAdapter(breedsAdapter);
        
        getBreeds = (Button)this.findViewById(R.id.get_breeds); 
        getBreeds.setEnabled(false);
        getBreeds.setOnClickListener(new OnClickListener() {
        	
			@Override
			public void onClick(View v) {
//				ProgressDialog progressDialog = new ProgressDialog(getApplicationContext());
//				progressDialog.setIndeterminate(true);
				methodProgress.setVisibility(View.VISIBLE);
				String response = executeMethodCall(METHOD_BREED_LIST, formatMethodArgument("animal", selectedAnimal));
				breedsAdapter.clear();
				parseXml(new ByteArrayInputStream(response.getBytes()), "breed", breedsAdapter);
				methodProgress.setVisibility(View.INVISIBLE);
			}
		});
        
        methodProgress = (ProgressBar) this.findViewById(R.id.progressBar);
    }
    
    private String executeMethodCall(String method, String arguments){
    	String responseString = null;
    	try {
    	HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response;
        String url = SERVICE_URL + method + "?" + API_KEY + arguments;
        response = httpclient.execute(new HttpGet(url));
        StatusLine statusLine = response.getStatusLine();
        if(statusLine.getStatusCode() == HttpStatus.SC_OK){
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            response.getEntity().writeTo(out);
            out.close();
            responseString = out.toString();
            //..more logic
        } else{
            //Closes the connection.
            response.getEntity().getContent().close();
            throw new IOException(statusLine.getReasonPhrase());
        }
    	} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return responseString;
    }
    
    private void parseXml(InputStream xml, String tag, ArrayAdapter<String> arrayAdapter){
    	try {
			DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			Document dom = builder.parse(xml);
			NodeList list = dom.getDocumentElement().getElementsByTagName(tag);
			for(int i=0; i<list.getLength(); i++){
				arrayAdapter.add(list.item(i).getFirstChild().getNodeValue());
			}
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    
    private String formatMethodArgument(String key, String value){
    	return "&" + key + "=" + value;
    }
    
    private Button getBreeds;
    private Spinner breeds;
    private ProgressBar methodProgress;
    private String selectedAnimal;
    private ArrayAdapter<String> breedsAdapter;
}